package org.bangumibuddy.utils;

import lombok.SneakyThrows;
import org.bangumibuddy.config.property.JwtProperties;
import org.bangumibuddy.constant.Constant;
import org.bangumibuddy.pojo.token.TokenData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
public class JwtManager {

    @Autowired
    JwtProperties jwtProperties;

    public TokenData creteTokens(String username,String email,String role){
        String token = createToken(username,email,role);
        String longlivedToken = createLonglivedToken(username,email,role);
        return TokenData.builder().token(token).longlivedToken(longlivedToken).build();
    }

    public TokenData creteTokens(Map claim){
        String token = JwtUtils.createJWT(jwtProperties.getSecret(), jwtProperties.getExpireTime(), claim);
        String longlivedToken = JwtUtils.createJWT(jwtProperties.getSecret(), jwtProperties.getRefreshExpire(), claim);

        return TokenData.builder().token(token).longlivedToken(longlivedToken).build();
    }

    public String createToken(String username,String email,String role) {
        Map<String, String> claim = new HashMap<>();
        claim.put(Constant.USERNAME,username);
        claim.put(Constant.EMAIL,email);
        claim.put(Constant.ROLE, role);

        return JwtUtils.createJWT(jwtProperties.getSecret(), jwtProperties.getExpireTime(), claim);
    }

    public String createToken(Map<String, String> claim) {
        return JwtUtils.createJWT(jwtProperties.getSecret(), jwtProperties.getExpireTime(), claim);
    }

    public String createLonglivedToken(String username,String email,String role){
        Map<String, String> claim = new HashMap<>();
        claim.put(Constant.USERNAME,username);
        claim.put(Constant.EMAIL,email);
        claim.put(Constant.ROLE, role);

        return JwtUtils.createJWT(jwtProperties.getSecret(), jwtProperties.getRefreshExpire(), claim);
    }

    public String createLonglivedToken(Map<String, String> claim){
        return JwtUtils.createJWT(jwtProperties.getSecret(), jwtProperties.getRefreshExpire(), claim);
    }

    @SneakyThrows
    public TokenData tryRefreshToken(String longlivedToken) {
        JwtUtils.verityToken(longlivedToken, jwtProperties.getSecret());
        Map claim = JwtUtils.getClaim(longlivedToken, jwtProperties.getSecret());

        return creteTokens(claim);
    }

}
